package com.serviceclient.scribe;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.serviceclient.model.ServiceClient;
import com.serviceinfo.model.ParameterInfo;
import com.servicerequest.model.ServiceRequest;
import com.servicerequestinfo.model.ServiceRequestInfo;

public class ScribeServiceClient implements ServiceClient {

	private String scheme;

	private String hostUrl;

	private String serviceUrl;

	public String getScheme() {
		return scheme;
	}

	public void setScheme(String scheme) {
		this.scheme = scheme;
	}

	public String getHostUrl() {
		return hostUrl;
	}

	public void setHostUrl(String hostUrl) {
		this.hostUrl = hostUrl;
	}

	public String getServiceUrl() {
		return serviceUrl;
	}

	public void setServiceUrl(String serviceUrl) {
		this.serviceUrl = serviceUrl;
	}

	@Override
	public ServiceRequest buildRequest(ServiceRequestInfo serviceRequest) {

		String method = serviceRequest.getServiceInfo().getServiceMethod();
		String url = scheme + "://" + hostUrl + serviceUrl + serviceRequest.getServiceInfo().getServiceUrl();

		ScribeServiceRequest.Builder scribeRequest = new ScribeServiceRequest.Builder(method, url);
		scribeRequest.addHeaderValues(serviceRequest.getHeaders());

		Map<ParameterInfo, List<Object>> queryValues = serviceRequest.getQueryValues();
		for (Entry<ParameterInfo, List<Object>> entry : queryValues.entrySet()) {
			String paramName = entry.getKey().getName();
			List<Object> list = entry.getValue();
			for (Object parameterValue : list) {
				scribeRequest.addQueryParam(paramName, String.valueOf(parameterValue));
			}
		}

		Map<ParameterInfo, List<Object>> formValues = serviceRequest.getFormValues();
		for (Entry<ParameterInfo, List<Object>> entry : formValues.entrySet()) {
			String paramName = entry.getKey().getName();
			List<Object> list = entry.getValue();
			for (Object parameterValue : list) {
				scribeRequest.addFormParam(paramName, String.valueOf(parameterValue));
			}
		}
		return scribeRequest.build();
	}
}
